package com.vains.util;

import com.vains.bean.Result;
import com.vains.constant.GlobalConstants;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * servlet 工具类
 *
 * @author vains
 * @date 2021/4/3 18:44
 */
@Slf4j
public final class ServletUtils {

    private ServletUtils() {}

    /**
     * 通过response将数据写回页面
     * @param response 响应对象
     * @param result 要写回的数据
     */
    public static void writeDataByResponse(HttpServletResponse response, Result<?> result) {
        response.setHeader(GlobalConstants.HEADER_KEY_CONTENT_TYPE, GlobalConstants.APPLICATION_JSON_UTF8);
        response.setCharacterEncoding(GlobalConstants.ENCODE_UTF8);
        String json = JsonUtils.objectCovertToJson(result);
        try {
            response.getWriter().println(json);
            response.getWriter().flush();
        } catch (IOException ex) {
            log.error("将数据写回页面时失败.", ex);
        }
    }

}
